package com.sskj.b70.v.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sskj.b70.MyAppLication;
import com.sskj.b70.R;
import com.sskj.b70.common.App;
import com.sskj.b70.common.Constants;
import com.sskj.b70.common.MoneyValueFilter;
import com.sskj.b70.common.adapter.BaseAdapter;
import com.sskj.b70.common.adapter.ViewHolder;
import com.sskj.b70.common.rxbus2.RxBus;
import com.sskj.b70.common.rxbus2.Subscribe;
import com.sskj.b70.common.rxbus2.ThreadMode;
import com.sskj.b70.common.widget.ToolBarLayout;
import com.sskj.b70.m.StockCoinBean;
import com.sskj.b70.m.bean.StockBean;
import com.sskj.b70.m.bean.TradeInfoBean;
import com.sskj.b70.m.bean.TransactionModel;
import com.sskj.b70.m.bean.rxbus.StockLevel;
import com.sskj.b70.m.bean.rxbus.StockLevelUpdate;
import com.sskj.b70.p.fragment.LevelTransactionFragmentPst;
import com.sskj.b70.utils.BottomSheetUtil;
import com.sskj.b70.utils.CheckUtil;
import com.sskj.b70.utils.ClickUtil;
import com.sskj.b70.utils.DisposUtil;
import com.sskj.b70.utils.EditChangeUtil;
import com.sskj.b70.utils.NumberUtil;
import com.sskj.b70.utils.RxSchedulersHelper;
import com.sskj.b70.utils.ToastUtil;
import com.sskj.b70.v.activity.BindMobileActivity;
import com.sskj.b70.v.activity.LoginActivity;
import com.sskj.b70.v.activity.MainActivity;
import com.sskj.b70.v.activity.MarketNewActivity;
import com.sskj.b70.v.activity.TradeActivity;
import com.sskj.b70.v.base.BaseFragment;
import com.sskj.b70.v.widget.BubbleSeekBar;
import com.sskj.b70.v.widget.NumberRunningTextView;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;


/**
 * 合约交易
 * create by Hey at 2018/4/26 9:14
 */

public class LevelTransactionFragment extends BaseFragment<MainActivity, LevelTransactionFragmentPst> implements OnRefreshListener {


    private BottomSheetDialog priceModeSheet;
    //    @BindView(R.id.transaction_user_balance)
//    TextView usefulNum;
    @BindView(R.id.toolBar)
    ToolBarLayout mToolBar;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout mSmartRefresh;
    @BindView(R.id.transaction_item_balance)
    TextView mTransactionItemBalance;
    @BindView(R.id.risk_ratio)
    TextView mRiskRatio;
    @BindView(R.id.transction_price_editText)
    EditText mTransctionPriceEditText;
    @BindView(R.id.transction_price_textView)
    TextView mTransctionPriceTextView;
    @BindView(R.id.transction_increase_price)
    TextView mTransctionIncreasePrice;
    @BindView(R.id.transction_decrease_price)
    TextView mTransctionDecreasePrice;
    @BindView(R.id.transaction_approximate)
    TextView mTransactionApproximate;
    @BindView(R.id.transaction_count)
    TextView mTransactionCount;
    @BindView(R.id.transction_sum_editText)
    EditText mTransctionSumEditText;
    @BindView(R.id.transaction_type)
    TextView mTransactionType;
    @BindView(R.id.transcation_seekbar)
    BubbleSeekBar mTransactionSeekBar;
    @BindView(R.id.inputLayoutLoss)
    TextInputLayout textInputLayoutLoss;
    @BindView(R.id.inputLayoutWin)
    TextInputLayout textInputLayoutWin;
    @BindView(R.id.priceNow)
    NumberRunningTextView mPriceNow;// 当前价格
    @BindView(R.id.changeRate)
    TextView mChangeRate;// 当前价格  右侧  百分比
    @BindView(R.id.highPrice)
    TextView mHighPrice;// 高 价格
    @BindView(R.id.lowPrice)
    TextView mLowPrice;   // 低  价格
    @BindView(R.id.tvRMB)
    TextView tvRMB;
    @BindView(R.id.stop_loss_value)
    TextView mStopLossValue;
    @BindView(R.id.etStopWin)
    EditText etStopWin;
    @BindView(R.id.etStopLoss)
    EditText etStopLoss;
    @BindView(R.id.target_profit_value)
    TextView mTargetProfitValue;
    @BindView(R.id.transaction_input)
    TextView mTransactionInput;
    @BindView(R.id.transaction_output)
    TextView mTransactionOutput;
    @BindView(R.id.transaction_history_all)
    TextView mTransactionHistoryAll;
    @BindView(R.id.radioGroup)
    RadioGroup mRadioGroup;
    @BindView(R.id.price_type_a)
    RadioButton mRadioBTTypeA;
    @BindView(R.id.price_type_b)
    RadioButton mRadioBTTypeB;
    @BindView(R.id.tv_detail_title_type)
    TextView tvDetailTitleType;
    @BindView(R.id.spinner)
    TextView mSpinner;
    @BindView(R.id.llPriceMode)
    LinearLayout llPriceMode;
    @BindView(R.id.transaction_sell_list)
    RecyclerView transactionSellList;
    @BindView(R.id.transaction_buy_list)
    RecyclerView transactionBuyList;
    @BindView(R.id.rlEditPrice)
    RelativeLayout rlEditPrice;
    @BindView(R.id.loading_layout)
    FrameLayout mLoadingLayout;
    @BindView(R.id.transaction_rmb)
    TextView transactionRmb;// 人民币
    @BindView(R.id.transaction_now_price)
    TextView nowPrice;

    private StockLevel mStockLevel;
    /**
     * 价格类型 ： 1: 市价   ；   2 ： 限价
     * 默认 限价
     */
    private int mType = 1;
    /**
     * 下单需要的数据
     */
    private StockBean mStockBean;
    /**
     * 当前股票的当前价格
     */
    private double mCurrentPriceD;

    private double mCurrentPriceD2;
    DecimalFormat mFormat = new DecimalFormat("0.0000");
    /**
     * 计算的交易额
     */
    private double mSumPrice;
    private String name = "";
    private double price;
    private String code = "";
    private double maxNum; //可输入的最大数量
    private double minNum; //可输入的最小数量
    private double minDealNum; //可交易的最小数量
    private String unit = "USDT";
    private double leverage = 20; //杠杆
    private double shouPer; //手续费
    private String baoPer = "100%";
    /**
     * 当前币种的浮动点差价格
     */
    private double mSpreadPrice;
    private BigDecimal mSpreadPriceBig;
    private Disposable riskDispo;
    private BaseAdapter<TransactionModel.AsksBean> sellAdapter;
    private BaseAdapter<TransactionModel.BidsBean> buyAdapter;
    private int buyNum = 5;
    private String coinType;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_level_transaction;
    }

    @Override
    public LevelTransactionFragmentPst getPresenter() {
        return new LevelTransactionFragmentPst();
    }

    //    public int status = 0;//0 买入，1 卖出，
    public boolean isLimitPrice = true; //是否市价 默认市价
    private String wallet = "0.00";


    public static LevelTransactionFragment newInstance(String code) {

        Bundle args = new Bundle();
        args.putString(Constants.CODE, code);
        LevelTransactionFragment fragment = new LevelTransactionFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (MyAppLication.isLogin()) {
                mPresenter.getUserInfo();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isHidden() && MyAppLication.isLogin()) {
            mPresenter.getUserInfo();
        }
    }

    /**
     * 长连接更新买卖和最新价格信息
     *
     * @param data 数据源
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setBuySell(TransactionModel data) {
        if (buyAdapter != null && sellAdapter != null && data != null && data.getBids() != null && data.getAsks() != null) {
            Flowable.just(data)
                    .filter(item -> item.getCode().equals(code))
                    .compose(RxSchedulersHelper.transformer())
                    .subscribe(transactionModel -> {
                        if (mLoadingLayout != null) {
                            mLoadingLayout.setVisibility(View.INVISIBLE);
                        }
                        if (transactionModel.getAsks().size() >= buyNum) {
                            buyAdapter.setNewData(transactionModel.getBids().subList(0, buyNum));
                        }
                        if (transactionModel.getBids().size() >= buyNum) {
                            sellAdapter.setNewData(transactionModel.getAsks().subList(0, buyNum));
                        }

                    });
        }

    }

    @Override
    public void initView() {
        if (!RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().register(this);
        }
        if (getArguments() != null) {
            code = getArguments().getString(Constants.CODE, Constants.DEFAULT_COIN);
        }
        mSmartRefresh.setRefreshHeader(new MaterialHeader(getActivity()));
        mSmartRefresh.setEnableLoadMore(false);
        mSmartRefresh.setOnRefreshListener(this);
        mToolBar.setRightButtonIcon(getResources().getDrawable(R.mipmap.icon_a_nor));
        mToolBar.setRightButtonOnClickLinster(view12 -> { //跳转股票详情
            MarketNewActivity.start(getActivity(), code);
        });
        mToolBar.setLeftButtonOnClickLinster(view1 -> mActivity.openDrawerLayout());
        initUpView();
        mStockBean = new StockBean();
        mStockLevel = mActivity.stockLevel;
        mPresenter.getStockCoinByCode(code);
        startRiskTimer();
        mPresenter.getPankou(code);

    }

    public void setTextAndAnim(String text) {
        if (text.equals("---")) {
            return;
        }
        setText(mTransctionPriceEditText, text);
        ScaleAnimation scaleAnimation1 = new ScaleAnimation(1.0f, 1.5f, 1.0f, 1.4f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation1.setDuration(500);
        ScaleAnimation scaleAnimation2 = new ScaleAnimation(1.5f, 1f, 1.4f, 1f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation2.setDuration(500);
        scaleAnimation1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mTransctionPriceEditText.startAnimation(scaleAnimation2);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mTransctionPriceEditText.startAnimation(scaleAnimation1);

    }

    private void initUpView() {
        transactionSellList.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, true));
        transactionBuyList.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        sellAdapter = new BaseAdapter<TransactionModel.AsksBean>(R.layout.item_recycler_transaction_sell, new ArrayList<>(), transactionSellList) {
            @Override
            public void bind(ViewHolder holder, TransactionModel.AsksBean item) {
                holder.setText(R.id.transaction_sell_id, holder.getLayoutPosition() + 1 + "");
                holder.setText(R.id.transaction_sell_price, NumberUtil.keep4(item.getPrice()));
                holder.setText(R.id.transaction_sell_num, NumberUtil.keep4(item.getTotalSize()));
                holder.getView(R.id.transaction_sell_item).setOnClickListener(view -> {
                    if (!isLimitPrice) {
                        setTextAndAnim(NumberUtil.keep4(item.getPrice()));
                    } else {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment8));
                    }
                });
            }
        };
        buyAdapter = new BaseAdapter<TransactionModel.BidsBean>(R.layout.item_recycler_transaction_sell, new ArrayList<>(), transactionBuyList) {
            @Override
            public void bind(ViewHolder holder, TransactionModel.BidsBean item) {
                holder.setText(R.id.transaction_sell_id, holder.getLayoutPosition() + 1 + "");
                holder.setText(R.id.transaction_sell_price, NumberUtil.keep4(item.getPrice()));
                holder.setText(R.id.transaction_sell_num, NumberUtil.keep4(item.getTotalSize()));
                holder.setTextColor(R.id.transaction_sell_price, ContextCompat.getColor(getActivity(), R.color.bull_cyan_blue));
                holder.getView(R.id.transaction_sell_item).setOnClickListener(view -> {
                    if (!isLimitPrice) {
                        setTextAndAnim(NumberUtil.keep4(item.getPrice()));
                    } else {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment8));
                    }
                });
            }
        };
        mRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.price_type_a://买入
                    if (mActivity.status != 0) {
                        mActivity.status = 0;
                        etStopWin.setText("");
                        etStopLoss.setText("");
                        mRadioBTTypeB.setTextColor(ContextCompat.getColor(getActivity(), R.color.bull_gray));
                        mRadioBTTypeA.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_down));
                        mTransactionSeekBar.setThumbColor(ContextCompat.getColor(mActivity, R.color.market_down));
                        mTransactionSeekBar.setSecondTrackColor(ContextCompat.getColor(mActivity, R.color.market_down));
                        mTransactionSeekBar.setBubbleColor(ContextCompat.getColor(mActivity, R.color.market_down));
                        updateUI();
                    }
                    break;
                case R.id.price_type_b://卖出
                    if (mActivity.status != 1) {
                        mActivity.status = 1;
                        etStopWin.setText("");
                        etStopLoss.setText("");
                        mRadioBTTypeB.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_up));
                        mRadioBTTypeA.setTextColor(ContextCompat.getColor(getActivity(), R.color.bull_gray));
                        mTransactionSeekBar.setThumbColor(ContextCompat.getColor(mActivity, R.color.market_up));
                        mTransactionSeekBar.setSecondTrackColor(ContextCompat.getColor(mActivity, R.color.market_up));
                        mTransactionSeekBar.setBubbleColor(ContextCompat.getColor(mActivity, R.color.market_up));
                        updateUI();

                    }
                    break;
            }
        });
        if (mActivity.mUserInfo != null) {
            mTransactionItemBalance.setText(NumberUtil.keepNoZero(mActivity.mUserInfo.getWallone()) + " USDT");
        }
        ClickUtil.click(mTransactionHistoryAll, () -> { //查看全部交易记录
            if (MyAppLication.isLogin()) {
                startActivity(new Intent(mActivity, TradeActivity.class));
            } else {
                startActivity(new Intent(mActivity, LoginActivity.class));
            }
        });
        //购买金额滑杆
        mTransactionSeekBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
                if (fromUser) {
                    double num = progress;
                    if (num <= minNum) {
                        num = minNum;

                    } else if (num >= maxNum) {
                        num = maxNum;
                    }
                    mTransctionSumEditText.setText(((int) num) + "");
                }
            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
            }

            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
            }
        });
        EditChangeUtil.onChange(etStopLoss, (Editable s) -> {
            if (mStockLevel == null) {
                return;
            }
            etStopLoss.setSelection(s.toString().length());


            if (TextUtils.isEmpty(s.toString())) {
                mStopLossValue.setText("");
                return;
            }
            if (s.toString().length() >= 2 && s.toString().indexOf("0") == 0) {
                etStopLoss.setText(s.toString().substring(1, s.toString().length()));
                mStopLossValue.setText(s.toString().substring(1, s.toString().length()));

            }
            if (mStockLevel != null) {

                if (Integer.valueOf(s.toString()) > mStockLevel.getStopLoss()) {
                    etStopLoss.setError(App.INSTANCE.getString(R.string.strLevelTransactionFragment19) + mStockLevel.getStopLoss());
                    etStopLoss.setText(mStockLevel.getStopLoss() + "");
                    mStopLossValue.setText(mStockLevel.getStopLoss() + "");
                }
//                else if (Integer.valueOf(s.toString()) < mStockLevel.getMinStopLoss()) {
//                    etStopLoss.setError(App.INSTANCE.getString(R.string.strLevelTransactionFragment22) + mStockLevel.getMinStopLoss());
//                    etStopLoss.setText(mStockLevel.getMinStopLoss() + "");
//                    mStopLossValue.setText(mStockLevel.getMinStopLoss() + "");
//                }
                else {
                    mStopLossValue.setText(Integer.valueOf(s.toString()) + "");

                }
            }

        });

        EditChangeUtil.onChange(etStopWin, s -> {
            if (mStockLevel == null) {
                return;
            }
            etStopWin.setSelection(s.toString().length());

            if (TextUtils.isEmpty(s.toString())) {
                mTargetProfitValue.setText("");
                return;
            }
            if (s.toString().length() >= 2 && s.toString().indexOf("0") == 0) {
                etStopWin.setText(s.toString().substring(1, s.toString().length()));
                mTargetProfitValue.setText(s.toString().substring(1, s.toString().length()));
            }
            if (mStockLevel != null) {
                if (Integer.valueOf(s.toString()) > mStockLevel.getStopProfit()) {
                    etStopWin.setError(App.INSTANCE.getString(R.string.strLevelTransactionFragment28) + mStockLevel.getStopProfit());
                    etStopWin.setText(mStockLevel.getStopProfit() + "");
                    mTargetProfitValue.setText(mStockLevel.getStopProfit() + "");
                }
//                else if (Integer.valueOf(s.toString()) < mStockLevel.getMinStopProfit()) {
//                    etStopWin.setError(App.INSTANCE.getString(R.string.strLevelTransactionFragment31) + mStockLevel.getMinStopProfit());
//                    etStopWin.setText(mStockLevel.getMinStopProfit() + "");
//                    mTargetProfitValue.setText(mStockLevel.getMinStopProfit() + "");
//                }
                else {
                    mTargetProfitValue.setText(Integer.valueOf(s.toString()) + "");

                }
            }
        });
        EditChangeUtil.onChange(mTransctionPriceEditText, s -> {
            mCurrentPriceD = Double.parseDouble(TextUtils.isEmpty(s.toString()) ? "0" : s.toString());

            if (TextUtils.isEmpty(s.toString()) || Double.isInfinite(maxNum) || Double.isNaN(maxNum)) {
                maxNum = 0;
            } else {
                calcuMostNum();
            }
//            usefulNum.setText(App.INSTANCE.getString(R.string.strLevelTransactionFragment36) + (int) maxNum + " " + coinType);
            mTransactionSeekBar.getConfigBuilder().max((int) maxNum).build();
            if (!TextUtils.isEmpty(mTransctionSumEditText.getText().toString().trim())) {
                //交易额 计算公式 : 最新价*购买数量/20
                double valueD = Double.valueOf(mTransctionSumEditText.getText().toString().trim());

                mSumPrice = calcuAllPrice(mCurrentPriceD, valueD);
                updateCountText(mSumPrice);
//                    mTransactionCount.setText(getString(R.string.transaction_count) + mFormat.format(mSumPrice) + unit);
            }
        });
        ClickUtil.click(llPriceMode, () -> {
            if (priceModeSheet == null) {
                priceModeSheet = BottomSheetUtil.getBottomSheet(getActivity(), App.INSTANCE.getString(R.string.strLevelTransactionFragment38), (recyclerView, position, v) -> {
                    priceModeSheet.dismiss();
                    changePriceMode(position);
                }, App.INSTANCE.getString(R.string.strLevelTransactionFragment39), App.INSTANCE.getString(R.string.strLevelTransactionFragment40));
            }
            priceModeSheet.show();
        });
        mTransctionPriceEditText.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(4)});
        EditChangeUtil.onChange(mTransctionSumEditText, editable -> {
            if (!MyAppLication.isLogin()) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment41));
                return;
            }
            if (TextUtils.isEmpty(mTransctionPriceEditText.getText()) || Double.valueOf(mTransctionPriceEditText.getText().toString()) == 0) {
                mTransactionCount.setText(getString(R.string.transaction_count) + "0.0000 " + unit);
                return;
            }
            if (!TextUtils.isEmpty(editable.toString())) {
                double valueD = formatDouble(editable);
                if (valueD > maxNum) { //大于最大数量
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment43));
                    editable.clear();
                    editable.append((int) maxNum + "");
                    mTransactionSeekBar.setCurrentProgress((int) maxNum);
                } else if (valueD < minNum) { //小于最小数量
                    editable.clear();
                    editable.append((int) minNum + "");
                    mTransactionSeekBar.setCurrentProgress((int) minNum);
                } else { //数量正常
                    //交易额 计算公式 : 最新价*购买数量/20
                    mSumPrice = calcuAllPrice(mCurrentPriceD, valueD);
                    updateCountText(mSumPrice);
//                        mTransactionCount.setText(getString(R.string.transaction_count) + mFormat.format(mSumPrice) + unit);
                    mTransactionSeekBar.setCurrentProgress((int) valueD);
                }
            } else { //数量为空，使用最小数量
//                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment46));
                mSumPrice = calcuAllPrice(mCurrentPriceD, minNum);
                mTransactionCount.setText(getString(R.string.transaction_count) + NumberUtil.keepMax4(mSumPrice) + unit);
//                TextSizeUtil.adjustTvTextSize(mTransactionCount,mTransactionCount.getWidth(),getString(R.string.transaction_count) + NumberUtil.keepMax4(mSumPrice) + unit);
                mTransactionSeekBar.setCurrentProgress((int) minNum);
            }
        });
        ClickUtil.click(mTransactionInput, () -> { //买入（买涨）
            mStockBean.otype = 1;
            placeOrder();
        });
        ClickUtil.click(mTransactionOutput, () -> { //卖出（买跌）
            mStockBean.otype = 2;
            placeOrder();
        });
    }

    private void startRiskTimer() {
        DisposUtil.close(riskDispo);
        riskDispo = Flowable.interval(1, TimeUnit.SECONDS)
                .onBackpressureDrop()
                .subscribe(i -> mPresenter.getRisk());
    }

    @Override
    public void initData() {
        super.initData();
        mPresenter.getNewInfo(code);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setStockLevel(StockLevel mStockLevel) {
        if (mPresenter != null) {
            mPresenter.getNewInfo(mStockLevel.getCode());
            mPresenter.getPankou(code);
        }
        this.mStockLevel = mStockLevel;
        mType = 1;
        isLimitPrice = true;
        updateUI();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (etStopWin != null) {
            etStopWin.setText("");
            etStopWin.setError(null);
            etStopLoss.setText("");
            etStopLoss.setError(null);
        }
        if (isVisibleToUser) {
            startRiskTimer();
            if (MyAppLication.isLogin()) {
                if (mPresenter != null) {
                    mPresenter.getUserInfo();
                }
            } else {
                updateWallet("0");
            }
        } else {
            DisposUtil.close(riskDispo);
        }
    }

    public void updateUI() {
        if (mSpinner != null) {
            etStopWin.getText().clear();
            etStopLoss.getText().clear();
            mSpinner.setText(isLimitPrice ? App.INSTANCE.getString(R.string.strLevelTransactionFragment39) : App.INSTANCE.getString(R.string.strLevelTransactionFragment40));
            mTransctionPriceTextView.setVisibility(isLimitPrice ? View.VISIBLE : View.GONE);
            rlEditPrice.setVisibility(isLimitPrice ? View.GONE : View.VISIBLE);
            if (mStockLevel == null) return;
            updateUserTitle();
            updateCoinData();
            mActivity.mTransactionFragmentUp = true;
            updateSaleAndSold();
            mTransctionPriceEditText.setText(String.valueOf(price));
            unit = name.split("/")[1];
            coinType = name.split("/")[0];
            mTransactionType.setText(coinType);
            mToolBar.setTitleLeft();
            mToolBar.setTitle(name);
            mTransctionSumEditText.getText().clear();
            mTransactionSeekBar.setCurrentProgress(0f);
            updateCountText(0.0);
//        usefulNum.setText(App.INSTANCE.getString(R.string.strLevelTransactionFragment36) + (int) maxNum + " " + coinType);
            mTransactionSeekBar.getConfigBuilder().max((int) maxNum).build();
            mTransactionSeekBar.getConfigBuilder().min((int) minNum).build();
            textInputLayoutLoss.setHint(App.INSTANCE.getString(R.string.strLevelTransactionFragment56) + mStockLevel.getMinStopLoss() + "~" + mStockLevel.getStopLoss());
            textInputLayoutWin.setHint(App.INSTANCE.getString(R.string.strLevelTransactionFragment58) + mStockLevel.getMinStopProfit() + "~" + mStockLevel.getStopProfit());
        }

    }

    private void updateCountText(double money) {
        if (mTransactionCount != null) {
            mTransactionCount.setText(String.format("%s %s %s", getString(R.string.transaction_count), mFormat.format(money), unit));
//            TextSizeUtil.adjustTvTextSize(mTransactionCount,mTransactionCount.getWidth(),getString(R.string.transaction_count) + " " + mFormat.format(money) + " " + unit);

        }
    }

    private void updateSaleAndSold() {
        if (mActivity.status == 0) { //买入
            if (mRadioGroup.getCheckedRadioButtonId() != R.id.price_type_a) {
                mRadioGroup.check(R.id.price_type_a);
            }
            mTransactionInput.setVisibility(View.VISIBLE);
            mTransactionInput.setText(App.INSTANCE.getString(R.string.strLevelTransactionFragment195));
            mTransactionInput.setBackground(getResources().getDrawable(R.drawable.shape_bull_cyan_blue));
            mTransactionOutput.setVisibility(View.GONE);
            mTransctionSumEditText.setHint(App.INSTANCE.getString(R.string.strLevelTransactionFragment64) + minDealNum);
        } else { //卖出
            if (mRadioGroup.getCheckedRadioButtonId() != R.id.price_type_b) {
                mRadioGroup.check(R.id.price_type_b);
            }
            mTransactionInput.setVisibility(View.GONE);
            mTransactionOutput.setVisibility(View.VISIBLE);
            mTransactionOutput.setText(App.INSTANCE.getString(R.string.strLevelTransactionFragment196));
            mTransactionOutput.setBackground(getResources().getDrawable(R.drawable.shape_bull_red));
            mTransctionSumEditText.setHint(App.INSTANCE.getString(R.string.strLevelTransactionFragment64) + minDealNum);
        }
    }


    private void updateCoinData() {
        name = mStockLevel.getName();
        code = mStockLevel.getCode();
        mCurrentPriceD = mCurrentPriceD2 = price = mStockLevel.getPrice();
        leverage = mStockLevel.getLeverage();
        if (mStockLevel.getShouPer() != 0) {
            shouPer = mStockLevel.getShouPer() / 100;
        }
        minDealNum = mStockLevel.getMinDealNum();
        mSpreadPrice = new BigDecimal(mStockLevel.getSlidingScalePrice() + "").multiply(new BigDecimal(mStockLevel.getSpread() + "")).doubleValue();
        mSpreadPriceBig = new BigDecimal(mStockLevel.getSlidingScalePrice() + "").multiply(new BigDecimal(mStockLevel.getSpread() + ""));
        calcuMostNum();
        if (minDealNum == 0) {
            minDealNum = 1;
        }
        mTransctionPriceTextView.setText(price + "");
        String trim = mTransctionPriceTextView.getText().toString().trim();

        if (mActivity.status == 0) {
            if (TextUtils.isEmpty(trim)) {
//                mCurrentPriceD = Double.valueOf(trim) + mSpreadPrice;
                mCurrentPriceD = Double.valueOf(trim);
            }
            mTransctionSumEditText.setHint(App.INSTANCE.getString(R.string.strLevelTransactionFragment72) + minDealNum);
        } else {
            if (TextUtils.isEmpty(trim)) {
                mCurrentPriceD = Double.valueOf(trim);
//                mCurrentPriceD = Double.valueOf(trim) - mSpreadPrice;
            }
            mTransctionSumEditText.setHint(App.INSTANCE.getString(R.string.strLevelTransactionFragment73));
        }
        minNum = 0;

    }

    /**
     * 切换显示价格
     *
     * @param buyPrice  买价
     * @param sellPrice 卖价
     */

    private void switchPrice(String buyPrice, String sellPrice) {
        if (mActivity.status == 0) { //买入
            mCurrentPriceD = price = Float.parseFloat(sellPrice);
        } else {
            mCurrentPriceD = price = Float.parseFloat(buyPrice);
        }
    }

    private void updateUserTitle() {
        if (MyAppLication.isLogin()) { //有登陆
            mTransactionItemBalance.setText(NumberUtil.keepNoZero(wallet) + " USDT");
        } else { //没登录
            wallet = "0.00";
            mTransactionItemBalance.setText("0.000" + " USDT");

        }

    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        if (mSmartRefresh != null) {
            mSmartRefresh.finishRefresh();
            if (MyAppLication.isLogin()) {
                mPresenter.getUserInfo();
            } else {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment41));
            }
            mPresenter.getStockCoinByCode(code);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefresh(StockLevelUpdate stockLevelUpdate) {
        if (!TextUtils.isEmpty(stockLevelUpdate.getCode())) {
            code = stockLevelUpdate.getCode();
        }
        if (MyAppLication.isLogin()) {
            mPresenter.getUserInfo();
        } else {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment41));
        }
        mPresenter.getStockCoinByCode(code);
    }


    public void updateWallet(String wallet) {
        this.wallet = wallet;
        updateUI();
    }

    public void onCreateOrderSuccess(boolean isWeituo) {
        //止盈止损初始化
        mStopLossValue.setText("");
        mTargetProfitValue.setText("");
        onRefresh((new StockLevelUpdate(code)));
//        startActivity(new Intent(getActivity(), TradeActivity.class).putExtra("index", isWeituo ? 1 : 0));
    }

    /**
     * 更新风险率
     *
     * @param data
     */
    public void updateRisk(TradeInfoBean data) {
        if (mRiskRatio != null) {
            mRiskRatio.setText(App.INSTANCE.getString(R.string.strLevelTransactionFragment83) + data.getProportion() + "%");
        }
    }


    private void placeOrder() {
        if (MyAppLication.isLogin()) {
            if (!checkPhone()) {
                return;
            }
            Double userBalance = Double.valueOf(mActivity.mUserInfo.getWallone());
            Double sumVlaue = mSumPrice;
            if (userBalance < sumVlaue) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment85));
                return;
            }

            mStockBean.buynum = mTransctionSumEditText.getText().toString().trim();
            if (TextUtils.isEmpty(mStockBean.buynum)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment86));
                return;
            }
            if (Double.valueOf(mStockBean.buynum) < minDealNum) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment72) + minDealNum);
                return;
            }
//                if (TextUtils.isEmpty(mActivity.mUserInfo.tpwd)) {
//                    ToastUtil.showShort(getResources().getString(R.string.none_zf_pwd));   // 请先设置支付密码
//                    startActivity(new Intent(mActivity, PayPwdSettingActivity.class));
//                    return;
//                }
            Double aDouble = Double.valueOf(mStockBean.buynum);
            if (aDouble <= 0) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment86));
                return;
            }
            mStockBean.type = mType;
            if (mType == 2) { //限价，选择用户输入的价格
                if (TextUtils.isEmpty(mTransctionPriceEditText.getText().toString().trim())) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment89));
                    return;
                } else if (Double.valueOf(mTransctionPriceEditText.getText().toString().trim()) <= 0) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment90));
                    return;
                }
                mStockBean.newprice = mTransctionPriceEditText.getText().toString().trim();
            } else { //市价，选择股票最新的价格
                mStockBean.newprice = mTransctionPriceTextView.getText().toString().trim();
                if (Double.valueOf(mStockBean.newprice) == 0 || TextUtils.isEmpty(mStockBean.newprice)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment90));
                    return;
                }
            }
            mStockBean.shopname = code;
            mStockBean.code = code;
            String stoploss = etStopLoss.getText().toString().trim();
            String stopwin = etStopWin.getText().toString().trim();
            if (TextUtils.isEmpty(stopwin)) {
                stopwin = "0";
            } else {
                if (Integer.parseInt(stopwin) > mStockLevel.getStopProfit()) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment28) + mStockLevel.getStopProfit());
                    return;
                }
                if (Integer.parseInt(stopwin) < mStockLevel.getMinStopProfit()) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment31) + mStockLevel.getMinStopProfit());
                    return;
                }
            }
            if (TextUtils.isEmpty(stoploss)) {
                stoploss = "0";
            } else {
                if (Integer.parseInt(stoploss) > mStockLevel.getStopLoss()) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment19) + mStockLevel.getStopLoss());
                    return;
                }
                if (Integer.parseInt(stoploss) < mStockLevel.getMinStopLoss()) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment22) + mStockLevel.getMinStopLoss());
                    return;
                }
            }

            mStockBean.stoploss = stoploss;
            mStockBean.stopwin = stopwin;

            mPresenter.createOrder(mStockBean, true, mType == 2);
        } else {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.strLevelTransactionFragment41));
            LoginActivity.start(getActivity());
        }
    }


    @OnClick({R.id.transction_decrease_price, R.id.transction_increase_price})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.transction_decrease_price:
                mCurrentPriceD2 = mCurrentPriceD2 + 0.0001;
                String formata = mFormat.format(mCurrentPriceD2);
                mCurrentPriceD = mCurrentPriceD2 = Double.valueOf(formata);
                mTransctionPriceEditText.setText(formata);
                break;
            case R.id.transction_increase_price:
                if (mCurrentPriceD2 > 0.0001) {
                    mCurrentPriceD2 = mCurrentPriceD2 - 0.0001;
                    String formatb = mFormat.format(mCurrentPriceD2);
                    mCurrentPriceD = mCurrentPriceD2 = Double.valueOf(formatb);
                    mTransctionPriceEditText.setText(formatb);
                }
                break;
        }
    }

    private void changePriceMode(int position) {
        if (position == 0) {
            mSpinner.setText(App.INSTANCE.getString(R.string.strLevelTransactionFragment39));
            isLimitPrice = true;
            mType = 1;
            mCurrentPriceD = TextUtils.isEmpty(mTransctionPriceEditText.getText().toString().trim()) ? 0 : Double.parseDouble(mTransctionPriceEditText.getText().toString().trim());
        } else {
            mSpinner.setText(App.INSTANCE.getString(R.string.strLevelTransactionFragment40));
            isLimitPrice = false;
            mCurrentPriceD = price;
            mType = 2;
        }
        updateUI();
    }

    private double formatDouble(Editable editable) {
        String value = editable.toString().trim();
        if (!CheckUtil.isOnlyPointNumber(value)) { //限制输入两位小数
//
            if (value.indexOf(".") > 0) {
                if (value.length() - value.indexOf(".") > 2) {
                    editable.delete(value.indexOf(".") + 3, value.length());
                }
            }
        }
        value = editable.toString().trim();
        return Double.valueOf(value);
    }

    /**
     * 计算可以购买的最大数量
     * wallet 钱包总金额
     * mCurrentPriceD 当前价格
     * leverage 杠杆
     * shouPer 手续费率
     * 计算公式 (总金额 /(当前价/杠+当前价×手续费）
     */
    private void calcuMostNum() {
        BigDecimal down = new BigDecimal(1).add(new BigDecimal(shouPer + "")).multiply(new BigDecimal(mCurrentPriceD + ""));
        if (down.doubleValue() == 0 || Double.valueOf(wallet) == 0) {
            maxNum = 0;
        } else {
            maxNum = new BigDecimal(wallet).multiply(new BigDecimal(leverage + ""))
                    .divide(down, 8, RoundingMode.DOWN).doubleValue();
        }
//        maxNum = (Double.parseDouble(wallet)) / (mCurrentPriceD / leverage + mCurrentPriceD * shouPer);
        maxNum = Math.floor(maxNum);
        if (Double.isNaN(maxNum) || Double.isInfinite(maxNum)) {
            maxNum = 0;
        }
    }

    /**
     * 计算总价格
     * price 单价
     * num 购买数量
     * leverage 杠杆
     * shouPer 手续费率
     * 这里的数量 已经计算了手续费（ count = （wallet * 杠杆 - wallet * 手续费） / 单价 ）
     * 计算公式 (price * num) / leverage
     */
    private double calcuAllPrice(double price, double num) {
//        BigDecimal allPriceBig = new BigDecimal(NumberUtil.keepMax4(price))
//                .multiply(new BigDecimal(NumberUtil.keepMax4(num)));
//        BigDecimal realAllPrice = allPriceBig
//                .divide(new BigDecimal(NumberUtil.keepMax4(leverage)))
//                .add(allPriceBig.multiply(new BigDecimal(NumberUtil.keepMax4(shouPer))));

//        Double testPrice = Double.valueOf(mTransctionPriceEditText.getText().toString());
//        double testNewPrice = Arith.add(testPrice, mSpreadPrice);
//        BigDecimal testNewPriceBig = mSpreadPriceBig.add(new BigDecimal(testPrice));
//        BigDecimal testBIg = testNewPriceBig.multiply(new BigDecimal(num))
//                .divide(new BigDecimal(leverage))
//                .add(testNewPriceBig.multiply(new BigDecimal(num)
//                        .multiply(new BigDecimal(shouPer))));
//        System.out.println(testBIg.doubleValue());
//        double test = (testNewPrice * num) / leverage + (testNewPrice * num) * shouPer;
//        if ()
        return (price * num) / leverage + (price * num) * shouPer / leverage; //交易额 计算公式 : 最新价*购买数量/20
    }

    public static LevelTransactionFragment newInstance() {
        LevelTransactionFragment fragment = new LevelTransactionFragment();
        return fragment;
    }

    @Subscribe(code = Constants.USER_LOGOUT, threadMode = ThreadMode.MAIN)
    public void logout() {
        updateUI();//初始化界面

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(StockCoinBean.StockProductVOBean stock) {
        if (stock.getCode().equals(code) && getActivity() != null) {
            if (tvRMB != null) {
                tvRMB.setText("≈" + stock.getCnyPrice() + "CNY");
                if (mStockLevel != null) {
                    mStockLevel.setPrice(new BigDecimal(stock.getPrice()).doubleValue());
                }
                if (!TextUtils.isEmpty(stock.getPrice())) {
                    setText(nowPrice, stock.getPrice());
                    if (transactionRmb != null) {
                        transactionRmb.setText("≈" + stock.getCnyPrice() + "CNY");
                    }
                    tvRMB.setText("≈" + stock.getCnyPrice() + "CNY");
                }
                if (stock.getChange() > 0) {
                    mChangeRate.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_down));
                    mPriceNow.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_down));
                    nowPrice.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_down));

                } else {
                    mChangeRate.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_up));
                    mPriceNow.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_up));
                    nowPrice.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_up));

                }
                mChangeRate.setText(stock.getChangeRate());
                mHighPrice.setText(NumberUtil.keepNoZoreMax4(stock.getHigh()));
                mLowPrice.setText(NumberUtil.keepNoZoreMax4(stock.getLow()));
                mPriceNow.setText(stock.getPrice());
            }
        }
    }

    public void onCreateOrderFail() {
        onRefresh((new StockLevelUpdate(code)));
    }

    public boolean checkPhone() {
        if (TextUtils.isEmpty(MyAppLication.getMobile())) {
            ToastUtil.showShort(getString(R.string.mine_bind_phone));
            BindMobileActivity.start(getActivity());
            return false;
        }
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
